#include "../DWMRICore/Fiber.h"
#include "../DWMRICore/HOT.h"
#include "../DWMRICore/Scalar.h"
#include "../DWMRICore/DTI.h"

#include <teem/ten.h>

#include <omp.h>

#define _USE_MATH_DEFINES
#include <math.h>
#include <time.h>

#include <string>

using namespace std;

char *pDTIPathname = NULL;
char *pHOTPathname = NULL;				/* input high order tensor pathname */
char *pWMMASKPathname = NULL;			/* input white matter mask pathname */
char *pBrainMASKPathname = NULL;		/* input brain mask pathname */
char *pModelSelectionPathname = NULL;	/* input model selection pathname */
char *pFiberPathname = NULL;			/* output fiber configure pathname */
float stepSize = 0.5f;
float maxLength = 10.0f;
float faThreshold = 0.1f;
float angleThreshold = 0.707f;
int scale = 1;


/* MLS fiber tracking parameters */
float MLSSize = 4.0f;
CPoint3F *pSamplePoints = NULL;
float *pSamplePointsWeight = NULL;

CDTI *pDTI = NULL;
CHOT *pHOT = NULL;					/* HOT */
CScalar *pBrainMASK = NULL;			/* brain mask */
CScalar *pWMMASK = NULL;			/* white matter mask */
CScalar *pModelSelection = NULL;	/* model selection */

void PrintUsage()
{
	printf("Usage: ");
	printf("HOTFiberTracking -hot <HOT> -brain_mask <Brain MASK> -wm_mask <White Matter MASK> -fiber <Fiber> [-stepsize <stepsize> -maxlength <maxlength> -fa_thresold <fa_threshold> -angle_threshold <fa_threshold> -scale <scale>]\n");
	printf("\n");
	//printf("-vec <VectorField> = input VectorField nrrd file\n");
	//printf("-fiber <Fiber> = output Fiber configure file\n");
	//printf("-stepsize <stepsize> = step size\n");
	//printf("-maxlength <maxlength> = maximum fiber length\n");
	//printf("-fa_threshold <fa_thresold> = FA threshold used to differ white matter and grey matter\n");
	//printf("-angle_threshold <angle_thresold> = angle threshold between two directions, in cosine\n");
	//printf("-scale <scale> = scale of the result\n");
}


int ParseArguments(const int argc, char *argv[])
{
	for (int i = 1; i < argc; ++i) {
		if (strcmp(argv[i], "-hot") == 0) {
			pHOTPathname = argv[++i];
		} else if (strcmp(argv[i], "-dti") == 0) {
			pDTIPathname = argv[++i];
		} else if (strcmp(argv[i], "-brain_mask") == 0) {
			pBrainMASKPathname = argv[++i];
		} else if (strcmp(argv[i], "-wm_mask") == 0) {
			pWMMASKPathname = argv[++i];
		} else if (strcmp(argv[i], "-fiber") == 0) {
			pFiberPathname = argv[++i];
		} else if (strcmp(argv[i], "-stepsize") == 0) {
			stepSize = (float)atof(argv[++i]);
		} else if (strcmp(argv[i], "-maxlength") == 0) {
			maxLength = (float)atof(argv[++i]);
		} else if (strcmp(argv[i], "-fa_threshold") == 0) {
			faThreshold = (float)atof(argv[++i]);
		} else if (strcmp(argv[i], "-angle_threshold") == 0) {
			angleThreshold = (float)atof(argv[++i]);
		} else if (strcmp(argv[i], "-scale") == 0) {
			scale = (uint)atoi(argv[++i]);
		} else {
            printf("unknown %s\n", argv[i]);
			return 1;		// error
		}
	}

	if (pHOTPathname == NULL || pBrainMASKPathname == NULL || pWMMASKPathname == NULL || pFiberPathname == NULL)
		return -2;

	return 0;
}


void CreateMLSSamplePoints()
{
	SafeDeleteArray(pSamplePoints);
	SafeDeleteArray(pSamplePointsWeight);
	pSamplePoints = new CPoint3F[SAMPLE_POINT_NUM];
	pSamplePointsWeight = new float[SAMPLE_POINT_NUM];

	pSamplePoints[0].m_x = 0.0f;
	pSamplePoints[0].m_y = 0.0f;
	pSamplePoints[0].m_z = 0.0f;
	pSamplePointsWeight[0] = 1.0f;

	clock_t seed = clock();
	srand(seed);

	for (int i = 1; i < SAMPLE_POINT_NUM; ++i) {
		bool flag = false;
		CPoint3F pt;
		while(!flag) {
			float a = (float)rand() / (float)RAND_MAX * 2.0f * (float)M_PI;
			float b = (float)rand() / (float)RAND_MAX * (float)M_PI;
			float r = (float)rand() / (float)RAND_MAX;

			pt.m_x = r * sinf(a) * sinf(b);
			pt.m_y = r * sinf(a) * cosf(b);
			pt.m_z = r * cosf(a);

			flag = true;
			for (int j = 0; j < i; ++j) {
				float dis = Distance(pSamplePoints[j], pt);
				if (dis < 0.3f) {
					flag = false;
					break;
				}
			}
		}

		pSamplePoints[i] = pt;
		pSamplePointsWeight[i] = InnerProduct(pSamplePoints[i], pSamplePoints[i]) * 4.0f;
		pSamplePointsWeight[i] = expf(pSamplePointsWeight[i] / -2.5f);
	}
}

void HOTMLSFilter(const CPoint3F pos, float *filteredHOT)
{
	float dti[7];
	pDTI->GetDTI(pos, dti);
	float m[9];
	TEN_T2M(m, dti);

	CPoint3F samples[SAMPLE_POINT_NUM];
	float length[SAMPLE_POINT_NUM];
	float max_length = 0.0f;
	for (uint i = 0; i < SAMPLE_POINT_NUM; ++i) {
		samples[i].m_x = pSamplePoints[i].m_x * m[0] + pSamplePoints[i].m_y * m[1] + pSamplePoints[i].m_z * m[2];
		samples[i].m_y = pSamplePoints[i].m_x * m[3] + pSamplePoints[i].m_y * m[4] + pSamplePoints[i].m_z * m[5];
		samples[i].m_z = pSamplePoints[i].m_x * m[6] + pSamplePoints[i].m_y * m[7] + pSamplePoints[i].m_z * m[8];
		length[i] = sqrtf(InnerProduct(samples[i], samples[i]));
		if (length[i] > max_length)
			max_length = length[i];
	}

	for (uint i = 0; i < SAMPLE_POINT_NUM; ++i) {
		samples[i].m_x = samples[i].m_x / max_length * MLSSize + pos.m_x;
		samples[i].m_y = samples[i].m_y / max_length * MLSSize + pos.m_y;
		samples[i].m_z = samples[i].m_z / max_length * MLSSize + pos.m_z;
	}

	uint n = pHOT->GetN();
	memset(filteredHOT, 0, sizeof(float)*n);
	float *temp_HOT = new float[n];
	float weight = 0.0f;
	for (uint i = 0; i < SAMPLE_POINT_NUM; ++i) {
		if (pBrainMASK->GetScalar(samples[i]) < 0.5f) {
			continue;
		}
		pHOT->GetHOT(samples[i], temp_HOT);

		for (uint j = 0; j < n; ++j) {
			filteredHOT[j] += pSamplePointsWeight[i] * temp_HOT[j];
		}
		weight += pSamplePointsWeight[i];
	}

	for (uint j = 0; j < n; ++j) {
		filteredHOT[j] = filteredHOT[j] / weight;
	}

	SafeDeleteArray(temp_HOT);
}

int ModelSelection(const CPoint3F pos)
{
	//uint x = uint(floor(pos.m_x));
	//uint y = uint(floor(pos.m_y));
	//uint z = uint(floor(pos.m_z));

	float x = pos.m_x;
	float y = pos.m_y;
	float z = pos.m_z;

	float model = pBrainMASK->GetScalar(x, y, z);
	if (model > 0.5f)
		return 2;
	//else if (model < 1.5f)
	//	return 1;
	else
		return 0;
}

int GetNextDirection(const CPoint3F pos, CVector3F *in, CVector3F *out)
{
	if (pBrainMASK->GetScalar(pos) < 0.5f) {
		return 0;
	}

	 if ((pWMMASK->GetScalar(pos) > 0.4f || pWMMASK->GetScalar(pos) < 0.2f))
		return 0;

	uint n = pHOT->GetN();
	float *hot = new float[n];
	HOTMLSFilter(pos, hot);
	//pHOT->GetHOT(pos, hot);
	CVector3F dirs[3];
	int count = pHOT->HOT2Directions(hot, dirs);
	SafeDeleteArray(hot);

	float max_v = 0.0f;
	int index = 0;
	for (int i = 0; i < count; ++i) {
		float v = InnerProduct(in, &(dirs[i]));
		if (fabs(v) > fabs(max_v)) {
			max_v = v;
			index = i;
		}
	}

	if (fabs(max_v) > angleThreshold) {
		if (max_v < 0.0f) {
			out->m_x = -dirs[index].m_x;
			out->m_y = -dirs[index].m_y;
			out->m_z = -dirs[index].m_z;
		} else {
			out->m_x = dirs[index].m_x;
			out->m_y = dirs[index].m_y;
			out->m_z = dirs[index].m_z;
		}
		return 1;
	} else {
		return 0;
	}
}

int TrackingFibers(CFiber **fibers, CPoint3F pos)
{
	uint n = pHOT->GetN();
	int model = ModelSelection(pos);

	float *hot = new float[n];
	HOTMLSFilter(pos, hot);
	//pHOT->GetHOT(pos, hot);
	CVector3F dirs[3];
	int count = 0;
	if (model == 1) {
		//count = pHOT->HOT2Directions_One(hot, dirs);
		count = pHOT->HOT2Directions(hot, dirs);
		count = 1;
	} else if (model == 2) {
		//count = pHOT->HOT2Directions_Two(hot, dirs);
		count = pHOT->HOT2Directions(hot, dirs);
		count = 1;
	} else if ((pWMMASK->GetScalar(pos) > 0.4f || pWMMASK->GetScalar(pos) < 0.2f)) {
		count = 1;
		dirs[0] = CVector3F(0, 0, 0);
	} else {
		count = 1;
		dirs[0] = CVector3F(0, 0, 0);
	}
	//int count = pHOT->HOT2Directions(hot, dirs);
	//count = 1;
	SafeDeleteArray(hot);

	*fibers = new CFiber[count];
	for (int i = 0; i < count; ++i) {
		Seed seed;
		seed.pos = pos;
		seed.dir = dirs[i];

		int innerSteps = 4;
		uint maxSteps = (uint)(maxLength / (stepSize * (float)innerSteps));
		uint fnum, bnum;
		CPoint3F *pF = new CPoint3F[maxSteps];
		CPoint3F *pB = new CPoint3F[maxSteps];
		CPoint3F lastPos;
		CVector3F lastDir;

		/* tracking forward */
		lastPos = seed.pos;
		lastDir = seed.dir;
		pF[0] = lastPos;
		for (fnum = 1; fnum < maxSteps; ++fnum) {
			CPoint3F nextPos;
			CVector3F nextDir;

			bool flag = true;
			for (int step = 0; step < innerSteps; ++step) {
				nextPos = lastPos + lastDir * stepSize;

				if (GetNextDirection(nextPos, &lastDir, &nextDir) == 0) {
					flag = false;
					break;
				}
				lastDir = nextDir;
				lastPos = nextPos;
			}
			if (flag == false)
				break;

			pF[fnum] = nextPos;
			lastDir = nextDir;
			lastPos = nextPos;
		}

		/* tracking backward */
		lastPos = seed.pos;
		lastDir = seed.dir;
		pB[0] = lastPos;
		bnum = 1;
		for (bnum = 1; bnum < maxSteps; ++bnum) {
			CPoint3F nextPos;
			CVector3F nextDir;

			bool flag = true;
			for (int step = 0; step < innerSteps; ++step) {
				nextPos = lastPos - lastDir * stepSize;

				if (GetNextDirection(nextPos, &lastDir, &nextDir) == 0) {
					flag = false;
					break;
				}
				lastDir = nextDir;
				lastPos = nextPos;
			}
			if (flag == false)
				break;

			pB[bnum] = nextPos;
			lastDir = nextDir;
			lastPos = nextPos;
		}

		(*fibers)[i].CreateFiber(pF, pB, fnum, bnum, &seed);

		SafeDeleteArray(pF);
		SafeDeleteArray(pB);
	}

	return count;
}

void HOTFiberTracking()
{
	uint w = pHOT->GetWidth();
	uint h = pHOT->GetHeight();
	uint d = pHOT->GetDepth();

	int sw = (int)w * scale;
	int sh = (int)h * scale;
	int sd = (int)d * scale;

	FILE *fp = fopen(pFiberPathname, "w");
	fprintf(fp, "%d %d %d %d %f %f\n", sw, sh, sd, scale, stepSize, maxLength);

	std::string pathname = pFiberPathname;
	size_t pos = pathname.find_last_of(SLASH);
	std::string path = pathname.substr(0, pos+1);

	omp_set_num_threads(16);

	for (int y = 124; y < 125; ++y) {
		printf("Fiber tracking on slice y = %d ... ", y);

		CFiber **fibers = new CFiber*[sw*sd];
		int *count = new int[sw*sd];
		memset(fibers, 0, sizeof(CFiber*)*sw*sd);
		memset(count, 0, sizeof(int)*sw*sd);

		for (int z = 0; z < sd; ++z) {	
#pragma omp parallel for schedule(dynamic, 1)
			for (int x = 0; x < sw; ++x) {
				CPoint3F pos = CPoint3F();
				//pos.m_x = (float)x/(float)scale + 1.0f / ((float)scale * 2.0f);
				//pos.m_y = (float)y/(float)scale + 1.0f / ((float)scale * 2.0f);
				//pos.m_z = (float)z/(float)scale + 1.0f / ((float)scale * 2.0f);
				pos.m_x = (float)x/(float)scale;
				pos.m_y = (float)y/(float)scale;
				pos.m_z = (float)z/(float)scale;
				int index = z * sw + x;
				count[index] = TrackingFibers(&(fibers[index]), pos);
			}
			float ff = float(z+1) / float(sd) * 100.0f;
			printf("\rFiber tracking on slice y = %d ... %.3f%%", y, ff);
		}

		char confPathname[PATHNAME_SIZE];
		char vertPathname[PATHNAME_SIZE];
		sprintf(confPathname, "%sslice_y=%08.04f.conf", path.c_str(), (float)y/(float)scale);
		sprintf(vertPathname, "%sslice_y=%08.04f.vert", path.c_str(), (float)y/(float)scale);
		fprintf(fp, "%s\t%s\n", confPathname, vertPathname);

		//SaveFibers(confPathname, vertPathname, fibers, count, sw, sd);
		SaveFibersAsVTK("C:\\Ziang\\Dataset\\Alex\\2X\\ForFiberTracking\\test.vtk", fibers, count, sw, sd);

		for (int i = 0; i < sd*sw; ++i) {
			SafeDeleteArray(fibers[i]);
		}
		SafeDeleteArray(fibers);
		SafeDeleteArray(count);

		printf("\rFiber tracking on slice y = %d ... 100.0%% Done.\n", y);
	}

	fclose(fp);
}

int main(int argc, char *argv[])
{
	if (ParseArguments(argc, argv) != 0) {
		PrintUsage();
		return 0;
	}

	pDTI = new CDTI();
	pDTI->OpenDTIFile(pDTIPathname);
	pHOT = new CHOT();
	pHOT->OpenHOTFile(pHOTPathname);
	pWMMASK = new CScalar();
	pWMMASK->OpenScalarFile(pWMMASKPathname);
	pBrainMASK = new CScalar();
	pBrainMASK->OpenScalarFile(pBrainMASKPathname);
	pModelSelection = new CScalar();
	pModelSelection->OpenScalarFile(pModelSelectionPathname);

	CreateMLSSamplePoints();

	HOTFiberTracking();

	SafeDelete(pDTI);
	SafeDelete(pHOT);
	SafeDelete(pWMMASK);
	SafeDelete(pModelSelection);

	return 0;
}
